<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>新建文章</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8"/>
    <link rel="stylesheet" href="/static/lib/layui/css/layui.css"/>
    <link rel="stylesheet" href="/static/css/x-admin/font.css">
    <link rel="stylesheet" href="/static/css/x-admin/xadmin.css">
    <link rel="stylesheet" href="/static/lib/editor.md/css/editormd.min.css"/>
    <link rel="stylesheet" href="/static/css/jquery/jquery.tag-editor.css"/>
    <link rel="stylesheet" href="/static/css/admin-index.css">
</head>
<body>
<div class="x-nav">
      <span class="layui-breadcrumb">
        <a>控制台</a>
        <a>文章管理</a>
        <a><cite>新建文章</cite></a>
      </span>
</div>
<div class="layui-anim layui-anim-scale x-body">
    <form id="article-form" class="layui-form" lay-filter="article-form">
        <#if article??>
            <input type="hidden" id="articleId" name="articleId" value="${article.getArticleId()?c}">
            <input type="hidden" id="articleUrl" name="articleUrl" value="${article.getArticleUrl()}">
        <#else>
            <input type="hidden" id="articleId" name="articleId">
            <input type="hidden" id="articleUrl" name="articleUrl">
        </#if>
        <div class="layui-col-md9">
            <div class="layui-form-item">
                <p class="form-title">标题</p>
                <div class="layui-input-block admin-input-block">
                    <#if article??>
                        <input type="text" name="articleTitle" class="layui-input" required lay-verify="required"
                               placeholder="请输入标题"
                               autocomplete="off" value="${article.getArticleTitle()}">
                    <#else>
                        <input type="text" name="articleTitle" class="layui-input" required lay-verify="required"
                               placeholder="请输入标题"
                               autocomplete="off">
                    </#if>
                </div>
            </div>
            <div class="layui-form-item">
                <p class="form-title">正文</p>
                <div id="editormd">
                    <textarea required lay-verify="required"
                              name="content"><#if article??>${article.getArticleContentMd()!}</#if></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <p class="form-title">
                    标签
                </p>
                <div>
                    <input type="text" autocomplete="off" required lay-verify="required" name="articleTags"
                           id="tag-list"/>
                </div>
            </div>
        </div>
        <div class="layui-col-md3 admin-post">
            <p class="form-title">操作</p>
            <div class="layui-card">
                <div class="layui-card-header"><h4>文章发布</h4></div>
                <div class="layui-card-body">
                    <div class="layui-form-item">
                        <div class="layui-input-block admin-input-block">
                            <button id="saveArticle" type="button" class="layui-btn">保存草稿</button>
                            <button id="postArticle" type="button" class="layui-btn layui-btn-normal">发布文章</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header"><h4>文章状态</h4></div>
                <div class="layui-card-body">
                    <div class="layui-form-item">
                        <div class="layui-input-block admin-input-block">
                            <select name="articleStatus" lay-verify="">
                                <#list articleStatusValues as status>
                                    <#if article??>
                                        <#if article.getArticleStatus() == status.getValue()>
                                            <option value="${status.getValue()}"
                                                    selected>${status.getMessage()}</option>
                                        <#else >
                                            <option value="${status.getValue()}">${status.getMessage()}</option>
                                        </#if>
                                    <#else>
                                    <option value="${status.getValue()}">${status.getMessage()}</option>
                                    </#if>
                                </#list>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header"><h4>文章操作</h4></div>
                <div class="layui-card-body">
                    <div class="layui-form-item">
                        <div class="layui-input-block admin-input-block">
                            <#if article??>
                                <input type="checkbox" name="allowComment" lay-filter="comment" title="允许评论"
                                       value="${article.getAllowComment()}">
                                <input type="checkbox" name="articleTop" lay-filter="top" title="是否置顶"
                                       value="${article.getArticleTop()}">
                            <#else>
                                <input type="checkbox" name="allowComment" lay-filter="comment" title="允许评论" value="1">
                                <input type="checkbox" name="articleTop" lay-filter="top" title="是否置顶" value="0">
                            </#if>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header"><h4>分类目录</h4></div>
                <div class="layui-card-body">
                    <div class="layui-form-item">
                        <div class="layui-input-block admin-input-block">
                            <select id="cate" name="category.cateId" lay-verify="" lay-filter="cate-select">
                            </select>
                        </div>
                        <hr class="layui-bg-gray">
                        <button id="cate-load" class="layui-btn layui-btn-normal layui-anim"
                                data-anim="layui-anim-scale" type="button"><i
                                class="layui-icon layui-icon-refresh"></i></button>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header"><h4>发布日期</h4></div>
                <div class="layui-card-body">
                    <div class="layui-form-item">
                        <div class="layui-input-block admin-input-block">
                            <input class="layui-input" name="createTime" id="createTime" lay-key="1">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header"><h4>标签选择</h4></div>
                <div class="layui-card-body">
                    <div class="layui-form-item">
                        <div class="layui-input-block admin-input-block">
                            <select id="tags-select" name="tags-select" lay-verify="" lay-search
                                    lay-filter="tags-select">
                            </select>
                            <hr class="layui-bg-gray">
                            <button id="tags-clear" class="layui-btn layui-btn-normal" type="button">清空标签</button>
                            <button id="tags-load" class="layui-btn layui-btn-normal layui-anim"
                                    data-anim="layui-anim-scale" type="button"><i
                                    class="layui-icon layui-icon-refresh"></i></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<script type="text/javascript" src="/static/js/jquery/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/static/lib/layui/layui.js" charset="utf-8"></script>
<script type="text/javascript" src="/static/js/x-admin/xadmin.js"></script>
<script type="text/javascript" src="/static/lib/editor.md/js/editormd.min.js"></script>
<script type="text/javascript" src="/static/js/jquery/jquery.tag-editor.min.js"></script>
<script type="text/javascript" src="/static/js/jquery/jquery.caret.min.js"></script>
<script type="text/javascript" src="/static/js/jquery/jQuery.Hz2Py-min.js"></script>
<script>
    $(function () {
        // 初始化编辑器
        var editor = editormd("editormd", {
            width: "100%",
            height: 620,
            path: "/static/lib/editor.md/lib/",
            saveHTMLToTextarea: true,
            imageUpload: true,
            syncScrolling: true,
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL: "/admin/",
            onfullscreen: function () {
                $("#editormd").css("z-index", "9999");
            },
            onfullscreenExit: function () {
                $("#editormd").css("z-index", "");
            }
        });
        // 初始化标签选择器
        $("#tag-list").tagEditor({placeholder: '请输入标签'});

        // 初始化发布日期
        layui.use('laydate', function () {
            var laydate = layui.laydate;
            var currentTime = new Date().getTime();
            laydate.render({
                elem: '#createTime',
                type: 'datetime',
                max: 0,
            value: <#if article??>'${article.getCreateTime()?string('yyyy-MM-dd HH:mm:ss')}'
                <#else>new Date(currentTime)</#if>
            });
        });
        // 添加标签
        layui.use('form', function () {
            var form = layui.form;
            form.on('select(tags-select)', function (data) {
                var tagName = data.elem[data.elem.selectedIndex].getAttribute('tagName');
                $('#tag-list').tagEditor('addTag', tagName);
            });
        });
        // 清空标签
        $("#tags-clear").on('click', function () {
            var tag_list = $('#tag-list');
            var tags = tag_list.tagEditor('getTags')[0].tags;
            for (var i = 0; i < tags.length; i++) {
                tag_list.tagEditor('removeTag', tags[i]);
            }
        });
        var cate_load = $("#cate-load");
        var tag_load = $("#tags-load");
        cate_load.on('click', function () {
            loadCategory();
        });
        tag_load.on('click', function () {
            loadTags();
        });

        // 初始化分类目录
        function loadCategory() {
            var options = "";
            $.ajax({
                url: "/admin/cate/cateAll",
                type: "post",
                dataType: "json",
                success: function (data) {
                    buildOptions(data['data'].categoryList);
                    var category = $("#cate");
                    category.html(options);
                    <#if article??>
                        category.val("#{article.getCategory().getCateId()}");
                    </#if>
                    renderFrom();
                }, error: function () {
                    layer.msg("初始化分类目录失败");
                }
            });

            function buildOptions(list) {
                if (list === null || list.length < 0) {
                    return;
                }
                for (var i = 0; i < list.length; i++) {
                    var cate = list[i];
                    var space = "";
                    for (var j = 1; j < cate.index; j++) {
                        space += "&nbsp;&nbsp;";
                    }
                    options += "<option value=\"" + cate.cateId + "\">" + space + "LV" + cate.index + "." + cate.cateName + "</option>\n";
                    if (cate.children.length > 0) {
                        buildOptions(cate.children);
                    }
                }
            }
        }

        $("#postArticle").on('click', function () {
            var articleStatus = $("select[name='articleStatus']").val();
            saveArticle(articleStatus);
        });

        $("#saveArticle").on('click', function () {
            // 草稿状态
            var articleStatus = 2;
            saveArticle(articleStatus);
        });

        /**
         * 保存文章
         *
         * @returns {boolean}
         */
        function saveArticle(articleStatus) {
            var articleTitle = $("input[name='articleTitle']");
            var articleUrl = articleTitle.toPinyin().toLowerCase().replace(" ", "-");
            var articleContentMd = editor.getMarkdown();
            var articleContentHTML = editor.getHTML();
            var tags = $("#tag-list").tagEditor('getTags')[0].tags.toString();
            var createTime = $("#createTime").val();
            var allowComment = $("input[name='allowComment']").val();
            var articleTop = $("input[name='articleTop']").val();
            var articleId = $("input[name='articleId']").val();
            if (articleTitle.val() === null || articleTitle.val() === '') {
                layer.msg("文章标题不能为空!");
                return false;
            }
            if (tags === null || tags === '') {
                layer.msg("文章标签不能为空!");
                return false;
            }
            if (articleId === null || articleId === '') {
                articleId = null;
            }
            $.ajax({
                url: "/admin/newArticle/saveArticle",
                type: "post",
                dataType: "json",
                data: {
                    articleTitle: articleTitle.val(),
                    articleUrl: articleUrl,
                    articleContentMd: articleContentMd,
                    articleContentHtml: articleContentHTML,
                    postTime: createTime,
                    categoryId: $("select[name='category.cateId']").val(),
                    allowComment: allowComment,
                    articleTop: articleTop,
                    articleStatus: articleStatus,
                    articleId: articleId,
                    tags: tags
                },
                success: function (data) {
                    layer.open({
                        content: data.message,
                        yes: function (index) {
                            if (data.code === 2002) {
                                extracted();
                            } else if (data.code === 2004) {
                                x_admin_close();
                            }
                            layer.close(index);
                        },
                        cancel: function (index) {
                            if (data.code === 2002) {
                                extracted();
                            } else if (data.code === 2004) {
                                x_admin_close();
                            }
                            layer.close(index);
                        }
                    });
                },
                error: function () {
                    layer.msg('文章发布失败');
                }
            });
        }

        // 初始化标签列表
        function loadTags() {
            $.ajax({
                url: "/admin/tags/showAllTags",
                type: "post",
                dataType: "json",
                success: function (data) {
                    var tags = $("#tags-select");
                    var allTags = data['data'].allTags;
                    var options = "";
                    for (var i = 0; i < allTags.length; i++) {
                        options += "<option value=\"" + allTags[i].tagId + "\"  tagName=\"" + allTags[i].tagName + "\">" + allTags[i].tagName + "</option>\n";
                    }
                    tags.html(options);
                    renderFrom();
                }, error: function () {
                    layer.msg("初始化标签失败");
                }
            });
        }

        // 重新加载表单
        function renderFrom() {
            layui.use('form', function () {
                var form = layui.form;
                form.render();
            });
        }

        function extracted() {
            var parentHtml = $("li[lay-id='2']", parent.document);
            parentHtml.children('span').html('所有文章');
            parentHtml.attr('lay-id', '3');
            $(window.frameElement).attr("src", "/admin/newArticle/all");
            $(window.frameElement).attr("tab-id", "3");
        }
        <#if article??>
            <#if article.getArticleTags()?size gt 0>
                <#list article.getArticleTags() as articleTags>
                    $("#tag-list").tagEditor('addTag', '<#if articleTags.getTag()??>${articleTags.getTag().getTagName()}</#if>');
                </#list>
            </#if>
        </#if>
        loadCategory();
        loadTags();
    });

    window.onbeforeunload = function (ev) {
        ev.returnValue = '您确定要离开吗？数据将不会被保存！';
        return ev.returnValue;
    };
</script>
<script>
    //演示动画
    $('.layui-anim').on('click', function () {
        var othis = $(this), anim = othis.data('anim');

        othis.removeClass(anim);

        setTimeout(function () {
            othis.addClass(anim);
        });
    });

    layui.use('form', function () {
        var form = layui.form;
        form.val("article-form", {
            "allowComment": true
        });
        form.on('checkbox(comment)', function (data) {
            var value = data.elem.checked ? 1 : 0;
            data.elem.setAttribute("value", value);
        });
        form.on('checkbox(top)', function (data) {
            var value = data.elem.checked ? 1 : 0;
            data.elem.setAttribute("value", value);
        });
    });
</script>
</body>
</html>